import pygame
#import sys
from didiball.Controls import Controls
from didiball.Team import Team
from didiball.Timer import Timer
from didiball.game import DiDiBallGame
from didiball.planes.Pitch import Pitch
from didiball.planes.Radar import Radar
from didiball.sprites.PassiveSprite import PassiveSprite
from didiball.planes.ViewPort import ViewPort
from didiball.screens.Instructions import Instructions
from didiball.screens.Options import Options
import pygame.locals as pl
#import ConfigParser
import os


class DiDiBallApp():
    DYNAMICS_GROUPS=['ball','human','ai.easy','ai.medium','ai.hard','ai.insane']

    def __init__(self, config):
        self.__config = config
        pygame.init()
        self.setup_window()
        font_file= os.path.join('img','fonts','BlueStone.ttf')
        self.main_font = pygame.font.Font(font_file, int(self.get_config('main','main.fontsize')))
        self.header_font = pygame.font.Font(font_file, int(self.get_config('main','header.fontsize')))
        c1= self.get_section('team0.keys')
        #Controls(pl.K_UP,pl.K_DOWN,pl.K_LEFT,pl.K_RIGHT,pl.K_DELETE,pl.K_INSERT),
        c2= self.get_section('team1.keys')
        #Controls(pl.K_w,pl.K_s,pl.K_a,pl.K_d,pl.K_c,pl.K_v)        
        self.team_controls= [Controls(c1),Controls(c2)]
        self.formation=(1,4,4,2)
        self.positions=([0.05],[0.3,0.2,0.2,0.3],[0.6,0.45,0.45,0.6],[0.7,0.78])
        self.setup_dynamics()
        self.setup_scoreboard()
        self.setup_pitch()
        self.setup_radar()
        self.setup_ball()
        self.setup_sounds()
        self.setup_timer()
        self.setup_viewport()
        self.setup_game()
        self.__screen.blit(self.__scoreboard, self.get_pos('scoreboard.dimensions'))
        self.setup_teams((True,True))
        #self.__screen.blit(self.__bg, self.__viewport.get_offset())

    def setup_timer(self):
        scoreb=self.get_pos('scoreboard.dimensions')
        w=self.get_dimensions('window.dimensions')
        self.__timer= Timer((w[0]/2,scoreb[1]+5))

    def setup_scoreboard(self):
        self.__scoreboard = pygame.Surface(self.get_dimensions('scoreboard.dimensions'))
        pygame.draw.rect(self.__scoreboard,self.get_rgb('pitch.linecolour'),self.__scoreboard.get_rect(),1)

    def setup_game(self):
        self.__game= DiDiBallGame(self.__pitch,self.__ball,self.__viewport,self.__radar,self.__sounds,self.__timer,float(self.__config.get('main','fps')), self.header_font, self.main_font)

    def get_cpu_dynamics(self,difficulty):
        if difficulty==1: return self.__dynamics['ai.easy']
        if difficulty==2: return self.__dynamics['ai.medium']
        if difficulty==3: return self.__dynamics['ai.hard']
        if difficulty==4: return self.__dynamics['ai.insane']
        
    def setup_teams(self,(each_is_cpu),cpu_skill=2):
        t0_is_cpu,t1_is_cpu = each_is_cpu
        team0__dynamics = t0_is_cpu and self.get_cpu_dynamics(cpu_skill) or self.__dynamics['human']
        team1__dynamics = t1_is_cpu and self.get_cpu_dynamics(cpu_skill) or self.__dynamics['human']
        team0 = Team(False, self.get_rgb('team0.textcolour'), self.__config.get('team0','name'), self.__config.get('team0','image'), team0__dynamics, self.formation, self.positions, self.__pitch, t0_is_cpu, self.team_controls[0], self.get_rgb('team0.sleevecolour'),self.get_rgb('team0.shortscolour') )
        team1 = Team(True, self.get_rgb('team1.textcolour'), self.__config.get('team1','name'), self.__config.get('team1','image'), team1__dynamics, self.formation, self.positions, self.__pitch, t1_is_cpu, self.team_controls[1], self.get_rgb('team1.sleevecolour'),self.get_rgb('team1.shortscolour') )

        self.__game.set_teams((team0,team1))

    def get_config(self,section,item):
        return self.__config.get(section, item)
        
    def get_pos(self,section):
        items= self.get_section(section)
        return (int(items['left']),int(items['top']))

    def get_section(self,section):
        items= self.__config.items(section)
        ret={}
        for x in items:
            ret[x[0]]=x[1]
        return ret

    def get_dimensions(self,section):
        items= self.get_section(section)
        return (int(items['width']),int(items['height']))

    def get_rgb(self,section):
        items= self.get_section(section)
        return (int(items['red']),int(items['green']),int(items['blue']))
        
    def setup_window(self):
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        self.__screen = pygame.display.set_mode(self.get_dimensions('window.dimensions'),0,32)
        self.__bg = pygame.Surface(self.get_dimensions('pitch.dimensions'))
        self.__bg.fill(self.get_rgb('window.background'))
        #icon = pygame.image.load(self.get_config('main','icon'))
        #pygame.display.set_icon(icon)
        pygame.display.set_caption("DiDiBall")


    def setup_sounds(self):
# sound
        mixer = pygame.mixer
        mixer.init()
        self.__sounds= {}
        #sounds['collision']=mixer.Sound(COLLISION_SOUND)
        #sounds['end']=mixer.Sound(END_SOUND)
        #sounds['goal']=mixer.Sound(GOAL_SOUND)

    def setup_dynamics(self):
        self.__dynamics= {}
        for x in self.DYNAMICS_GROUPS:
                self.__dynamics[x] = self.get_section("dynamics.{0}".format(x))
                
    def setup_ball(self):
        bc= self.get_section('ball')
        ball_img= pygame.image.load(bc['image']).convert_alpha()
        vp= self.get_section('viewport.border')
        w= self.get_dimensions('window.dimensions')
        self.__ball= PassiveSprite((int(vp['left'])/2+w[0]/2,int(vp['top'])/2+w[1]/2),0,float(self.__dynamics['ball']['max_speed'])*0.5,ball_img, self.__dynamics['ball'])

    def setup_viewport(self):
        #w= self.get_dimensions('window.dimensions')
        #vp= self.get_section('viewport.border')
        #vprect= pygame.Rect(int(vp['left']),int(vp['top']),w[0]-int(vp['right'])-int(vp['left']),w[1]-int(vp['top'])-int(vp['bottom']))
        vprect= self.__screen.get_rect()
        viewport= ViewPort(self.__screen,self.__pitch)
        #viewport= pygame.Surface((w[0]-int(vp['right'])-int(vp['left']),w[1]-int(vp['top'])-int(vp['bottom'])))
        #pygame.draw.rect(self.__screen,(0,0,255), vprect, 2)
        self.__viewport= viewport
        #self.__bg.blit(self.__viewport,(int(vp['left']),int(vp['top'])))
        self.__bg.blit(self.__pitch.get_surface(),vprect)

    def setup_radar(self):
        r= float(self.get_config('radar','scale'))
        o= self.get_pos('radar.pos')
        i= self.get_dimensions('radaritem.dimensions')
        #pitchoffset
        p= self.get_dimensions('pitch.dimensions')
        w= self.get_dimensions('window.dimensions')
        pitch_offset= (p[0]-w[0]/2,p[1]-w[1]/2)
        self.__radar= Radar(self.__pitch,r,o,pitch_offset,i)
        self.__radar.blit_to(self.__screen)

    def setup_pitch(self):
        p= self.get_dimensions('pitch.dimensions')
        #w= self.get_dimensions('window.dimensions')
        other_dimensions={}
        other_dimensions['area']= self.get_dimensions('area.dimensions')
        other_dimensions['sixyard']= self.get_dimensions('sixyard.dimensions')
        other_dimensions['goal']= self.get_section('goal.dimensions')
        other_dimensions['circle']= int(self.get_config('centre.circle','radius')) #no floats for radii
        pitch_rect= pygame.Rect(0,0,p[0],p[1])
        pitch= Pitch(pitch_rect, self.__scoreboard, other_dimensions)
        self.__pitch=pitch

    def controls(self,teams_are_cpu):
        controls=[]
        if teams_are_cpu[0]:
            controls.append(None)
        else:
            controls.append(self.team_controls[0].to_ordered_pair_of_lists())
            
        if teams_are_cpu[1]:
            controls.append(None)
        else:
            controls.append(self.team_controls[1].to_ordered_pair_of_lists())
        return controls
            
    def loop(self):
        while 1:
            # python api doesnt have ordered dicts, so 2 arrays instead
            opts=['human vs cpu','human vs human','cpu vs human','cpu vs cpu']
            results=[(True,False),(False,False),(False,True),(True,True)]
            iscreen=Options(self.__screen,self.__bg,self.main_font,self.header_font,self.__ball,"Choose Players",opts,results,2)
            players= iscreen.loop()

            opts=['1 minute','3 mins','5 mins','10 mins']
            results=[1,3,5,10]
            dscreen=Options(self.__screen,self.__bg,self.main_font,self.header_font,self.__ball,"Duration",opts,results,2)
            duration= dscreen.loop()
                   
            csskill= None
            if players[0]==True or players[1]==True:
                opts=['Beginner','Easy','Medium','Hard']
                results=[1,2,3,4]
                csscreen=Options(self.__screen,self.__bg,self.main_font,self.header_font,self.__ball,"Difficulty",opts,results,2)
                csskill=csscreen.loop()
            controls= self.controls(players)
            colours= [(125,25,25),(25,25,125)]
            names= ['Red Rackams','Blue Meanies']
            iscreen=Instructions(self.__screen,self.__bg,self.main_font,self.header_font,controls,colours,names)
            pygame.time.wait(2000)
            iscreen.loop()
            self.__screen.blit(self.__bg, (0,0))
            pygame.display.update()
            self.setup_teams(players,csskill)
            self.__game.loop(self.__screen,self.__bg,duration)
